package com.greenplayer.greenplayer;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public String vUrl = "http://116.255.187.43/";
    private long exitTime = 0;
    private View myView = null;
    private WebView webView;

    private LinearLayout frameLayout;
    private LinearLayout actionLayout;
    private ProgressDialog waitDialog = null;
    private WebChromeClient chromeClient = null;
    private WebChromeClient.CustomViewCallback myCallBack = null;
    private ImageView[] ivArray = new ImageView[4];
    private ProgressBar pbProgress;

    private static final int STOPSPLASH = 0;
    //time in milliseconds
    private static final long SPLASHTIME = 3000;
    private int staus = 0;
    private LinearLayout splash;
    private TextView tv;
    private WebView webInfo;
    private Animation animatinoGone;
    private Animation myAnimation_Alpha;

    public MainActivity() {
        actionLayout = null;
        frameLayout = null;
    }

    private Handler splashHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOPSPLASH:
//                    splash.startAnimation(animatinoGone);
                    splash.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        //隐藏标题栏
        boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        //标题栏隐藏
        getSupportActionBar().hide();//隐藏掉整个ActionBar，包括下面的Tabs

        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);

        //隐藏虚拟按键
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        //LinearLayout init
        frameLayout = (LinearLayout) findViewById(R.id.video_view);

        actionLayout = (LinearLayout) findViewById(R.id.action1);
        actionLayout.setVisibility(View.GONE);

        //Dialog init  页面跳转提示
        this.initDialog(null, null);

        //WebView setting
        this.initWebView(savedInstanceState);

        //ImageView init
        ivArray[0] = (ImageView) findViewById(R.id.ivHeat);
        ivArray[1] = (ImageView) findViewById(R.id.ivHome);
        ivArray[2] = (ImageView) findViewById(R.id.ivSearch);
        ivArray[3] = (ImageView) findViewById(R.id.ivUser);
        this.initImageView(-1);

        // Load opened URL in the application instead of standard browser
        this.initOkHttp();

        //进度条
        pbProgress = (ProgressBar) findViewById(R.id.pb_progress);

        //装载首页
        doHome(myView);

        //广告页面
        this.initWebInfo("");
        splash = (LinearLayout) findViewById(R.id.splashscreen);
        tv = (TextView) findViewById(R.id.info);
        tv.setText("正在建立数据连接");

//        splash.startAnimation(myAnimation_Alpha);
//        splash.setVisibility(View.GONE);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = STOPSPLASH;
                splashHandler.sendMessage(msg);
            }
        }, SPLASHTIME);

        //装载其他Activity
//        Intent mainIntent = new Intent(MainActivity.this,SplashActivity.class);
//        MainActivity.this.startActivity(mainIntent);
        //载入qq.com
//        webView.loadUrl(vUrl);
    }

    private void initWebInfo(String url) {
        webInfo = (WebView) findViewById(R.id.webinfo);
        //隐藏控件，目前为隐藏，未启用
        webInfo.setVisibility(View.GONE);
        //WebView加载web资源
        webInfo.loadUrl(url);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webInfo.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
    }

    public void initWebView(Bundle SIS) {
        // 设置WebView属性，能够执行Javascript脚本
//        String ua = "Mozilla/5.0 (Linux; Android 7.0; EVA-AL00 Build/HUAWEIEVA-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36";
//        wv.getSettings().setUserAgentString(ua);

        //webView init
        webView = (WebView) findViewById(R.id.webview);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        //webView Client init
        chromeClient = new MyChromeClient();
        webView.setWebChromeClient(chromeClient);
        webView.setWebViewClient(new MyWebviewCient());

        // 去掉滚动条
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);

        webView.getSettings().setJavaScriptEnabled(true); // 开启Javascript支持
        webView.getSettings().setLoadsImagesAutomatically(true);// 设置可以自动加载图片
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //不使用缓存
//        webView.getSettings().setAppCacheEnabled(true);// 应用可以有缓存
//        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 优先使用缓存
//        webView.getSettings().setAppCacheMaxSize(10 * 1024 * 1024);// 缓存最多可以有10M
        webView.getSettings().setDomStorageEnabled(true);// 设置可以使用localStorage
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        webView.getSettings().setGeolocationEnabled(true);// 启用地理定位
        webView.getSettings().setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        //webView.setScrollBarStyle(0);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上
        webView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        //加速WebView加载的方法
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH); // 提高渲染的优先级

        // 设置可自由缩放网页
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setBuiltInZoomControls(true);
        // 自适应屏幕
        webView.getSettings().setUseWideViewPort(false);
        webView.setVisibility(View.VISIBLE);

        if (SIS != null) {
            webView.restoreState(SIS);
        }
    }

    public void initDialog(String Title, String Msg) {
        waitDialog = new ProgressDialog(this);
//        waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        waitDialog.setTitle((Title == null) ? "友情提示" : Title);
        waitDialog.setMessage((Msg == null) ? "loading..." : Msg);
        waitDialog.setIndeterminate(false);
        waitDialog.setCancelable(true);
        waitDialog.setIndeterminate(false);
//        waitDialog.hide();
    }

    /**
     * OkHttp init
     */
    public void initOkHttp() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder1 = new Request.Builder();
        Request request = builder1.get().url("http://www.lsbfq.xyz:8000/ck/cache.php?userIp=101.23.120.185&url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        mTvResult.setText(res);
                        Log.e("okHttpResult:", res);
                    }
                });
            }
        });
    }

    //后退
    @Override
    public void onBackPressed() {
        if (myView == null) {
            super.onBackPressed();
        } else {
            chromeClient.onHideCustomView();
        }
    }

    //暂停
    @Override
    protected void onPause() {
        webView.reload();
        super.onPause();
    }

    //android webView点击返回键返回上一个html
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            chromeClient.onHideCustomView();
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                this.exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 捕捉返回事件按钮
     * <p>
     * 因为此 Activity 继承 TabActivity 用 onKeyDown 无响应，所以改用 dispatchKeyEvent
     * 一般的 Activity 用 onKeyDown 就可以了
     */
/*    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.e("dispatchKeyEvent:", "");
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            chromeClient.onHideCustomView();
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                this.exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }*/

    /**
     * 退出程序
     */
    private void exitApp() {
        // 判断2次点击事件时间
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            this.onPause();
            this.finish();
        }
    }

    public class MyWebviewCient extends WebViewClient {
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
            if (request != null && request.getUrl() != null) {
                String scheme = request.getUrl().getScheme().trim();
                if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
                    return super.shouldInterceptRequest(view, new WebResourceRequest() {
                        @Override
                        public Uri getUrl() {
                            Log.e("vURL:", request.getUrl().toString());
                            return Uri.parse(request.getUrl().toString());
                        }

                        @SuppressLint("NewApi")
                        @Override
                        public boolean isForMainFrame() {
                            return request.isForMainFrame();
                        }

                        @Override
                        public boolean isRedirect() {
                            return false;
                        }

                        @SuppressLint("NewApi")
                        @Override
                        public boolean hasGesture() {
                            return request.hasGesture();
                        }

                        @SuppressLint("NewApi")
                        @Override
                        public String getMethod() {
                            return request.getMethod();
                        }

                        @SuppressLint("NewApi")
                        @Override
                        public Map<String, String> getRequestHeaders() {
                            return request.getRequestHeaders();
                        }
                    });
                }
            }
            return super.shouldInterceptRequest(view, request);
        }


        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
//            view.loadUrl(url);
//            return true;

            if (url.contains("index61705")) {
                Intent i = new Intent(MainActivity.this, MainActivity.class);
                startActivity(i);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            waitDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            waitDialog.dismiss();
        }
    }

    public class MyChromeClient extends WebChromeClient {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            Log.e("onShowCustomView:", "");
            if (myView != null) {
                callback.onCustomViewHidden();
                return;
            }
            frameLayout.removeView(webView);
            frameLayout.addView(view, 0);
            myView = view;
            myCallBack = callback;
            frameLayout.setVisibility(View.VISIBLE);
            //test
            frameLayout.bringToFront();
            //设置横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            //设置全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

//            android.support.v7.app.ActionBar actionBar = getSupportActionBar();
//            if (actionBar != null) {
////                actionBar.setDisplayHomeAsUpEnabled(true);
//                getSupportActionBar().hide();//隐藏掉整个ActionBar，包括下面的Tabs
//            }
        }

        @Override
        public void onHideCustomView() {
            Log.e("onHideCustomView:", "");
            if (myView == null) {
                return;
            }
            frameLayout.removeView(myView);
            myView = null;
            frameLayout.addView(webView, 0);
            myCallBack.onCustomViewHidden();
            //test
            // 设置竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            // 取消全屏
            final WindowManager.LayoutParams attrs = getWindow()
                    .getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

//            android.support.v7.app.ActionBar actionBar = getSupportActionBar();
//            if (actionBar != null) {
////                actionBar.setDisplayHomeAsUpEnabled(false);
//                getSupportActionBar().show();
//            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            // TODO Auto-generated method stub
            Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        // Set progress bar during loading
        public void onProgressChanged(WebView view, int newProgress) {
//            MainActivity.this.setProgress(newProgress * 100);
            super.onProgressChanged(view, newProgress);
            Log.d("progress", "ProgressChanged++  " + newProgress);
            if (newProgress == 100) {
                // 网页加载完成
                pbProgress.setVisibility(View.GONE);
            } else {
                // 加载中
                pbProgress.setVisibility(View.VISIBLE);
                //设置加载进度
                pbProgress.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    public void doHome(View View) {
        initImageView(0);
//        webView.loadUrl(vUrl + "index.html");
        webView.loadUrl("http://h5.tv189.com/csite/wap/output/yytindex");
//        webView.loadUrl("http://192.168.99.137/hot");
//        webView.loadUrl("http://themolitor.com/vysual_html_video/index.html");
    }

    public void doVideo(View View) {
        initImageView(1);
//        webView.loadUrl("http://lsbfq.xyz:8000/ck/mobile.php?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
//        webView.loadUrl("http://player.a2yy.com/playm3u8/?url=http://v.youku.com/v_show/id_XMTM0MzczMjc0MA==.html");
//        webView.loadUrl("http://lsbfq.xyz:8000/ck/video");
//        webView.loadUrl("http://lsbfq.xyz");
//        webView.loadUrl("http://www.mrppj.com/");
//        webView.loadUrl("http://m.mrppj.com/m/index.php?m=vod-play-id-23777-src-1-num-9.html");
//        webView.loadUrl(vUrl + "rank.html");
        webView.loadUrl("http://h5.tv189.com/csite/wap/output/yytindex");
    }

    public void doSearch(View View) {
//        webView.loadUrl("http://www.lsbfq.xyz:8000");
//        webView.loadUrl("http://www.youku.com");
//        webView.loadUrl("http://www.runoob.com/try/try.php?filename=tryhtml5_video_all");
//        webView.loadUrl("http://www.6ayy.com/play/49374-0-0.html");
//        webView.loadUrl(vUrl);
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this).setTitle("搜索")
                .setIcon(android.R.drawable.ic_search_category_default)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "搜索内容不能为空！" + input, Toast.LENGTH_LONG).show();
                        } else {
                            webView.loadUrl("http://www.vipjiexi.com/vip.php?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
//                            Intent intent = new Intent();
//                            intent.putExtra("content", input);
//                            intent.setClass(MainActivity.this, SearchActivity.class);
//                            startActivity(intent);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    public void doUser(View View) {
        new AlertDialog.Builder(MainActivity.this).setTitle("系统提示")//设置对话框标题
                .setMessage("功能未开放！")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        // TODO Auto-generated method stub
//                        finish();
                    }
                }).show();//在按键响应事件中显示此对话框
//        initImageView(3);
//        webView.loadUrl("http://lsbfq.xyz:8000/ck/test.html");
//        webView.loadUrl("http://lsbfq.xyz:8000/ck/api");
    }

    public void doTv(View View) {
        initImageView(2);
        webView.loadUrl("http://dt.weiyunbo.cn/index.php");
    }

    public void doExit(View View) {
//        Android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
//        System.exit(0);   //常规Java、c#的标准退出法，返回值为0代表正常退出
        finish();
    }

    public void doRefresh(View View) {
//        webView.reload();
//        webView.loadUrl("http://www.lsbfq.xyz:8000/ck/?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
//        webView.loadUrl("http://player.a2yy.com/playm3u8/?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
//        webView.loadUrl("http://www.vipjiexi.com/vip.php?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
//        webView.loadUrl("http://www.lsbfq.xyz:8000/ck/hub.php?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
        webView.loadUrl("http://lsbfq.xyz:8000/ck/mobile.php?url=http://v.youku.com/v_show/id_XMjQ4OTA4ODQyMA==.html");
    }

    /**
     * 处理ImageView图片tint
     *
     * @param Index -1 0 1 2 3 4 ....
     *              -1 为全部
     */
    private void initImageView(int Index) {
        for (int i = 0; i < ivArray.length; i++) {
            if (Index != i) {
                ivArray[i].setColorFilter(Color.LTGRAY);
            } else {
                ivArray[i].setColorFilter(Color.GRAY, PorterDuff.Mode.DST_IN);
            }
        }
        if (-1 == Index) {
            ivArray[0].setColorFilter(Color.GRAY, PorterDuff.Mode.DST_IN);
        }
    }
}